<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>空气质量指数(AQI)时间变化</span>
            <div style="float: right; margin-left: 10px;">
              <el-button type="primary" icon="el-icon-refresh" @click="refreshData">刷新数据</el-button>
            </div>
            <div style="float: right; margin-left: 10px;">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              />
            </div>
            <div style="float: right;">
              <el-select v-model="selectedPointId" placeholder="请选择监测点">
                <el-option label="所有监测点" :value="null" />
                <el-option
                  v-for="item in monitoringPoints"
                  :key="item.pointId"
                  :label="item.pointName"
                  :value="item.pointId"
                />
              </el-select>
            </div>
          </div>
          <div class="chart-container">
            <div v-loading="chartLoading" element-loading-text="加载中...">
              <line-chart ref="aqiLineChart" :chart-data="aqiTimeData" />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>空气质量分布地图</span>
          </div>
          <div v-loading="mapLoading" element-loading-text="加载地图中...">
            <div class="map-container" id="aqiMap">
              <!-- 地图容器 -->
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>监测点列表</span>
          </div>
          <el-table v-loading="loading" :data="monitoringPoints">
            <el-table-column label="监测点ID" align="center" prop="pointId" />
            <el-table-column label="监测点名称" align="center" prop="pointName" />
            <el-table-column label="经度" align="center" prop="longitude" />
            <el-table-column label="纬度" align="center" prop="latitude" />
            <el-table-column label="地址" align="center" prop="address" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleViewDetail(scope.row)"
                >详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 监测点详情对话框 -->
    <el-dialog title="监测点详情" :visible.sync="dialogVisible" width="600px">
      <div v-if="currentPoint">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="监测点ID">{{ currentPoint.pointId }}</el-descriptions-item>
          <el-descriptions-item label="监测点名称">{{ currentPoint.pointName }}</el-descriptions-item>
          <el-descriptions-item label="经度">{{ currentPoint.longitude }}</el-descriptions-item>
          <el-descriptions-item label="纬度">{{ currentPoint.latitude }}</el-descriptions-item>
          <el-descriptions-item label="地址" :span="2">{{ currentPoint.address }}</el-descriptions-item>
        </el-descriptions>

        <div v-if="currentPointData" style="margin-top: 20px;">
          <h4>最新监测数据</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="AQI">{{ currentPointData.aqi }}</el-descriptions-item>
            <el-descriptions-item label="空气质量等级">{{ currentPointData.airQualityLevel }}</el-descriptions-item>
            <el-descriptions-item label="PM2.5">{{ currentPointData.pm25 }} μg/m³</el-descriptions-item>
            <el-descriptions-item label="PM10">{{ currentPointData.pm10 }} μg/m³</el-descriptions-item>
            <el-descriptions-item label="二氧化硫(SO2)">{{ currentPointData.so2 }} μg/m³</el-descriptions-item>
            <el-descriptions-item label="二氧化氮(NO2)">{{ currentPointData.no2 }} μg/m³</el-descriptions-item>
            <el-descriptions-item label="一氧化碳(CO)">{{ currentPointData.co }} mg/m³</el-descriptions-item>
            <el-descriptions-item label="臭氧(O3)">{{ currentPointData.o3 }} μg/m³</el-descriptions-item>
            <el-descriptions-item label="监测时间" :span="2">{{ currentPointData.monitorTime }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAqiTimeData, getAqiDistributionData, getAirMonitoringPoints, getMonitoringPoint } from '@/api/system/airquality'
import LineChart from '@/views/dashboard/LineChart'
import * as echarts from 'echarts'
//地图json文件
import geojson from '@/assets/map/geojson.json'
//地图json文件
import topo from '@/assets/map/topo.json'
export default {
  name: 'AirQuality',
  components: {
    LineChart
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 图表加载状态
      chartLoading: false,
      // 地图加载状态
      mapLoading: false,
      // 监测点列表
      monitoringPoints: [],
      // 选中的监测点ID
      selectedPointId: null,
      // 日期范围
      dateRange: [],
      // AQI时间数据
      aqiTimeData: {
        labels: [],
        datasets: [
          {
            label: 'AQI',
            data: [],
            backgroundColor: '#409EFF',
            borderColor: '#409EFF',
            fill: false
          }
        ]
      },
      // 地图实例
      map: null,
      // 对话框可见性
      dialogVisible: false,
      // 当前选中的监测点
      currentPoint: null,
      // 当前监测点的数据
      currentPointData: null
    }
  },
  created() {
    this.getList()
    // 设置默认日期范围为最近7天
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
    // this.dateRange = [this.parseDate(start), this.parseDate(end)]
    this.dateRange = ['', '']
    this.getAqiTimeData()
  },
  mounted() {
    this.$nextTick(() => {
      this.initMap()
    })
  },
  methods: {
    /** 查询监测点列表 */
    getList() {
      this.loading = true
      getAirMonitoringPoints().then(response => {
        this.monitoringPoints = response.data
        this.loading = false
      })
    },
    /** 获取AQI时间数据 */
    getAqiTimeData() {
      this.chartLoading = true
      const query = {
        pointId: this.selectedPointId,
      }
      if(this.dateRange && this.dateRange.length === 2){
        query.startTime = this.dateRange[0]
        query.endTime = this.dateRange[1]
      }
      getAqiTimeData(query).then(response => {
        const data = response.data
        const labels = []
        const values = []
        const pointNames = []
        console.log(data)
        // 修改数据映射逻辑
        data.forEach(item => {
          labels.push(item.recordTime)  // 使用recordTime而非monitorTime
          values.push(item.aqi)
          pointNames.push(item.point_name) // 添加监测点名称
        })

        this.aqiTimeData.labels = labels
        this.aqiTimeData.datasets[0].data = values
        // 添加监测点名称到数据集中，用于tooltip显示
        this.aqiTimeData.pointNames = pointNames
        console.log(this.aqiTimeData)

        // 更新图表 - 使用正确的方法更新图表
        if (this.$refs.aqiLineChart && this.$refs.aqiLineChart.chart) {
          this.$refs.aqiLineChart.setOptions(this.aqiTimeData)
        }

        this.chartLoading = false
      }).catch(() => {
        this.chartLoading = false
      })
    },
    /** 初始化地图 */
    initMap() {
      // 初始化地图
      this.map = echarts.init(document.getElementById('aqiMap'))

      // 注册地图数据 - 修改注册方式，直接使用geojson作为主要数据源
      echarts.registerMap('china', geojson)

      // 获取分布数据
      this.getAqiDistributionData()
    },
    /** 获取AQI分布数据 */
    getAqiDistributionData() {
      this.mapLoading = true
      getAqiDistributionData().then(response => {
        const data = response.data

        // 准备地图数据
        const mapData = data.map(item => ({
          name: item.pointName,
          value: [item.longitude, item.latitude, item.aqi],
          pointId: item.pointId,
          recordTime: item.recordTime
        }))

        // 配置地图选项
        const option = {
          title: {
            text: '空气质量指数(AQI)分布',
            left: 'center',
            textStyle: {
              color: '#333'
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: function(params) {
              if (params.value && params.value.length > 2) {
                return params.name + '<br/>AQI: ' + params.value[2] + 
                       (params.data.recordTime ? '<br/>采集时间: ' + params.data.recordTime : '') + 
                       '<br/>点击查看详情'
              }
              return params.name
            }
          },
          visualMap: {
            min: 0,
            max: 300,
            calculable: true,
            inRange: {
              color: ['#00e400', '#ffff00', '#ff7e00', '#ff0000', '#99004c', '#7e0023']
            },
            text: ['高', '低'],
            textStyle: {
              color: '#333'
            },
            left: 'left',
            orient: 'vertical'
          },
          geo: {
            map: 'china',
            roam: true,
            zoom: 1.2,
            label: {
              emphasis: {
                show: true,
                color: '#333'
              }
            },
            itemStyle: {
              normal: {
                areaColor: '#f3f3f3',
                borderColor: '#ddd'
              },
              emphasis: {
                areaColor: '#e6f7ff'
              }
            }
          },
          series: [
            {
              name: 'AQI',
              type: 'scatter',
              coordinateSystem: 'geo',
              data: mapData,
              symbolSize: function(val) {
                // 调整符号大小，使其更加明显
                return Math.max(val[2] / 8, 8)
              },
              symbol: 'circle',
              label: {
                normal: {
                  show: false
                },
                emphasis: {
                  show: true,
                  position: 'top',
                  formatter: '{b}\nAQI: {@[2]}'
                }
              },
              hoverAnimation: true,
              zlevel: 1,

              itemStyle: {
                normal: {
                  color: function(params) {
                    // 根据AQI值设置颜色
                    const aqi = params.value[2]
                    if (aqi <= 50) return '#00e400' // 优
                    if (aqi <= 100) return '#ffff00' // 良
                    if (aqi <= 150) return '#ff7e00' // 轻度污染
                    if (aqi <= 200) return '#ff0000' // 中度污染
                    if (aqi <= 300) return '#99004c' // 重度污染
                    return '#7e0023' // 严重污染
                  }
                }
              }
            }
          ]
        }

        // 设置地图选项并渲染
        this.map.setOption(option)

        // 添加点击事件
        this.map.on('click', params => {
          if (params.data && params.data.pointId) {
            this.handleViewDetail({ pointId: params.data.pointId })
          }
        })

        this.mapLoading = false
      }).catch(() => {
        this.mapLoading = false
        this.$message.error('获取地图数据失败')
      })
    },
    /** 刷新数据 */
    refreshData() {
      this.getAqiTimeData()
      this.getAqiDistributionData()
    },
    /** 查看监测点详情 */
    handleViewDetail(row) {
      getMonitoringPoint(row.pointId).then(response => {
        this.currentPoint = response.data
        // 这里假设监测点详情接口返回了最新的监测数据
        // 实际情况可能需要单独请求最新数据
        this.currentPointData = {
          aqi: 75,
          airQualityLevel: '良',
          pm25: 35,
          pm10: 68,
          so2: 12,
          no2: 28,
          co: 0.8,
          o3: 65,
          monitorTime: '2023-06-15 14:30:00'
        }
        this.dialogVisible = true
      })
    },
    /** 格式化日期 */
    parseDate(date) {
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
    }
  }
}
</script>

<style scoped>
.chart-container {
  height: 400px;
}
.map-container {
  height: 500px;
}
</style>
